package com.hp.bon.sgw.service;

import static com.hp.bon.sgw.Constants.LOG;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;

import com.hp.bon.sgw.bean.SensitivtyCfg;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.start.SpringContext;
import com.hp.bon.sgw.util.Comutils;

/**
 * 敏感字段控制（单例）
 * 
 * @author yudan
 * 
 */
public class SensitivtyCtrlService implements ConfigListener {
	//private static final Logger logger = LoggerFactory.getLogger(SensitivtyCtrlService.class);

	private static SensitivtyCtrlService instance;

	public static SensitivtyCtrlService getInstance() {
		if (instance == null) {
			instance = new SensitivtyCtrlService();
			instance.init();

			SpringContext.getInstance().getConfigService().addConfigListener(instance);
		}
		return instance;
	}

	private SensitivtyCtrlService() {}
	
	private void init(){}

	/**
	 * 敏感字段控制
	 * @param 
	 * @return
	 */
	public void checkSencitivtyCtrl(CallParam callParam, Object ack) {
		String hostId = callParam.getUserName();
		String serviceContextId = callParam.getServiceContextId();
		String cfgKey = SensitivtyCfg.getCfgKey(hostId, serviceContextId);
		
		SensitivtyCfg cfg = SpringContext.getInstance().getConfigService().getSensitivtyCfgMap().get(cfgKey);
		if (cfg == null) {
			return;
		}
		String level = cfg.getLevel();
		String safeLeve = cfg.getSafeLevel();
		if(safeLeve.equalsIgnoreCase("A")){
			return;
		}
		if((safeLeve.equalsIgnoreCase("B") && level.equals("3")) || safeLeve.equalsIgnoreCase("C")){
			setValueByPath(ack, cfg.getField(), "");
		}
	}
	
	private void setValueByPath(Object ack, String xmlTag, String value) {
		if (ack instanceof XmlMessage) {
			try {
				if (xmlTag == null)
					return;
				if(((XmlMessage) ack).getDATA() == null)
					return;
				Element e = null;
				Document doc = Comutils.parseText(((XmlMessage) ack).getDATA());
				e = doc.getRootElement();
				org.dom4j.Node keyNode = e.selectSingleNode(xmlTag);
				if (keyNode != null){
					String sensiText = convertToSensitivtyTxt(keyNode.getText());
					keyNode.setText(sensiText);
				}
				String xmlText = doc.asXML();
				((XmlMessage) ack).setDATA(xmlText.substring(xmlText.indexOf("\n")));
			} catch (Exception e) {
				LOG.warn("setValueByPath exception:", e);
			}
		}
	}
	
	private String convertToSensitivtyTxt(String orgTxt){
		if(orgTxt == null || orgTxt.length() == 0){
			return "";
		}

		String paintTxt = orgTxt.substring(0, orgTxt.length()/2);
		return StringUtils.rightPad(paintTxt, orgTxt.length(), "*");
	}
	
	@Override
	public Set<String> monitorConfKeys() {
		return new HashSet<String>();
	}

	@Override
	public void onConfigUpdated(String updatedKey) {
		;
	}
	
}
